<template>
  <BaseCard>
    <!-- 标题 -->
    <div class="top-outer-layer">
      <div class="border-left"></div>
      <div class="add-text">{{ addOrUpdate }}服务包</div>
    </div>
    <div class="ser-info">服务包信息</div>
    <!-- {{ formItem }} -->
    <el-form :model="formItem" label-width="auto" :rules="rules" require-asterisk-position="right">
      <el-row>
        <el-col :span="8">
          <el-form-item label="服务包名称" prop="name">
            <el-input v-model="formItem.name" placeholder="请输入" clearable
              style="width: 200px; height: 40px;margin-bottom: 16px;" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="服务包类型" prop="type">
            <el-select v-model="formItem.type" placeholder="请输入" clearable
              style="width: 200px; height: 40px;margin-bottom: 16px;">
              <el-option :label="item.type" :value="item.type" v-for="(item, index) in servicePackageTypeData"
                :key="index" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="订购价格" prop="price">
            <el-input v-model="formItem.price" pplaceholder="请输入" clearable
              style="width: 200px; height: 40px;margin-bottom: 16px;" />
            <div style="margin-bottom: 20px; margin-left: 5px ; color: #ccc;">元/年</div>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="8">
          <el-form-item label="服务对象">
            <el-input v-model="formItem.client" placeholder="请输入" clearable
              style="width: 200px; height: 40px;margin-bottom: 16px;" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="服务包标签">
            <el-select v-model="formItem.tagIds" placeholder="请输入" clearable
              style="width: 200px; height: 40px;margin-bottom: 16px;">
              <el-option :label="item.name" :value="item._id" v-for="item in tagData.rows" :key="item._id" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="签约周期" prop="period">
            <el-select v-model="formItem.period" placeholder="请输入" clearable
              style="width: 200px; height: 40px;margin-bottom: 16px;">
              <el-option label="Zone one" value="shanghai" />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-form-item label="续约情况" style="margin-bottom: 16px;">
        <el-radio-group v-model="formItem.renew" style="width: 200px; height: 40px;">
          <el-radio :value="1">可续签</el-radio>
          <el-radio :value="0">不可续签</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="服务包图片">
        <el-upload class="upload-demo" :action="`${baseURL}/images/upload`" :show-file-list="false"
          :on-success="handleAvatarSuccess" style="width: 200px; height: 40px;">
          <div class="form-image">
            <img v-if="formItem.image" :src="formItem.image" class="form-image" />
            <span class="load-image" v-else>+上传图片</span>
          </div>
          <template #tip>
            <div class="el-upload__tip">
              图片尺寸800*600px,可上传多张
            </div>
          </template>
        </el-upload>
      </el-form-item>
      <el-form-item label="服务介绍" style="margin-top: 150px;">
        <el-input v-model="formItem.intro" type="textarea" placeholder="请输入" clearable
          style="width: 580px; height: 120px; margin-bottom: 16px;" />
      </el-form-item>
    </el-form>
    <img src="../../assets/u402.png" alt="">
    <div class="add-button">
      <div>服务项目</div>
      <el-button type="primary" @click="openAddDialog = true">添加服务项目</el-button>
    </div>

    <el-dialog v-model="openAddDialog" title="选择服务项目" width="800">
      <el-table :data="serviceItemsData.rows" stripe
        style="width: 100%;margin-top: 16px;font-size: 12px; font-weight: lighter;"
        @selection-change="handleSelectionChange"
        :header-cell-style="{ backgroundColor: 'rgba(242, 242, 242, 0.498039215686275)', color: '#515a6e', fontWeight: 'lighter' }"
        row-key="_id">
        <el-table-column type="selection" width="50"></el-table-column>
        <el-table-column property="_id" label="负责人姓名" />
        <el-table-column property="name" label="电话" />
        <el-table-column property="count" label="机构地址" />
        <el-table-column property="type" label="机构地址" />
        <el-table-column property="intro" label="机构地址" />
      </el-table>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="openAddDialog = false">取消</el-button>
          <!-- 点击确认了之后再将选中的数据赋值给表单的数据 -->
          <el-button type="primary" @click="currentSelection">
            确认
          </el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 表格 -->
    <OtherTable :data="serviceItemIds" :columns="columns" v-model="formItem.serviceItemIds">
      <template #action="{ row }">
        <el-button type="danger" link size="small" @click="onDelete(row._id)">删除</el-button>
      </template>
    </OtherTable>

    <img src="../../assets/u402.png" alt="" style="margin-top: 20px;">
    <div class="add-button">服务详情字段</div>
    <el-form :model="formItem" label-width="auto" style="margin-top: 16px;padding: 20px 20px 0;">
      <el-form-item label="病情描述">
        <el-input v-model="formItem.user" type="textarea" placeholder="请输入" clearable
          style="width: 580px; height: 120px; margin-bottom: 16px;" />
        <img src="../../assets/u6819_mouseOver.png" class="write-img">
        <img src="../../assets/u6818_mouseOver.png" class="write-img">
        <img src="../../assets/u6817_mouseOver.png" class="write-img">
      </el-form-item>
      <el-form-item label="健康指导">
        <el-input v-model="formItem.user" type="textarea" placeholder="请输入" clearable
          style="width: 580px; height: 120px; margin-bottom: 16px;" />
        <img src="../../assets/u6819_mouseOver.png" class="write-img">
        <img src="../../assets/u6818_mouseOver.png" class="write-img">
        <img src="../../assets/u6817_mouseOver.png" class="write-img">
      </el-form-item>
      <el-form-item label="备注">
        <el-input v-model="formItem.user" type="textarea" placeholder="请输入" clearable
          style="width: 580px; height: 120px; margin-bottom: 16px;" />
        <img src="../../assets/u6819_mouseOver.png" class="write-img">
        <img src="../../assets/u6818_mouseOver.png" class="write-img">
        <img src="../../assets/u6817_mouseOver.png" class="write-img">
      </el-form-item>
      <el-form-item label=" ">
        <div class="add-one">+新增一条字段</div>
      </el-form-item>
    </el-form>
    <img src="../../assets/u402.png" style="margin-bottom: 20px;margin-top: 10px;">
    <el-button type="primary" @click="onSubmit">提交审核</el-button>
    <el-button @click="onBack">返回</el-button>
  </BaseCard>
</template>

<script setup>
import { computed, onMounted, ref } from 'vue';
import BaseCard from '../../components/base-card/BaseCard.vue';
import OtherTable from '../../components/base-table/OtherTable.vue';
import { useFindData } from '../../composables/findData';
import { useRouter } from 'vue-router';
import { useRoute } from 'vue-router';
import { addServicePackageApi, getServiceByIdApi, updateServicePackageApi } from '../../api/servicePacksge';

const { serviceItemsData, getServiceItemAsync, servicePackageTypeData, getServicePackageTypeAsync, servicePackageData, getServicePackageDataAsync, tagData, getTagAsync } = useFindData()
// 打开新增服务项目的弹窗
const openAddDialog = ref(false)
// 选中的复选框的数据
const router = useRouter()
const route = useRoute()
// 要修改的服务包的id
console.log(route.params._id);

const formItem = ref({
  name: '',
  type: '',
  price: '',
  client: '',
  tagIds: [],
  period: '1年',
  renew: '',
  image: '',
  intro: '',
  serviceItemIds: []
})
onMounted(() => {
  getServiceItemAsync()
  getServicePackageTypeAsync()
  getDetailsById()
})
// 拿到要编辑的id 数据回显 根据id 获取一个服务包的详情
const getDetailsById = () => {
  getServiceByIdApi({
    _id: route.params._id
  }).then(res => {
    if (res.code == 200) {
      console.log(res);
      formItem.value = res.data
    }
  })
}
// 修改数据
const getUpdate = () => {
  updateServicePackageApi({
    ...formItem.value,
    ...serviceItemIds.value
  }).then(res => {
    if (res.code == 200) {
      ElMessage({
        message: '修改数据成功',
        type: 'success',
      })
    }
  })
}
// 选中的复选框的数据
const serviceItemIds = ref([]);

const handleSelectionChange = (rows) => {
  serviceItemIds.value = rows; // 自动更新选中的数据
  // console.log("当前选中的数据：", selectedRows.value);
};
const currentSelection = () => {
  openAddDialog.value = false
  // 拿到选中的对象
  formItem.value.serviceItemIds = serviceItemIds.value;
  // console.log(formItem.value);
}
// 删除选中的新增项目的数据
const onDelete = (_id) => {
  serviceItemIds.value = serviceItemIds.value.filter(item => item._id != _id)
}
// 发送增加的请求
const getData = () => {
  addServicePackageApi({
    ...formItem.value,
    ...serviceItemIds.value
  }).then(res => {
    if (res.code == 200) {
      ElMessage({
        message: '提交成功',
        type: 'success',
      })
    }
  })
}
const onSubmit = () => {
  if (route.params._id) {
    // 修改
    getUpdate()
  } else {
    getData()
    // 添加成功后返回上一个页面 并且获取到数据库最新的数据渲染
    getServicePackageDataAsync()
  }
  router.back()
}

// 上传图片
const baseURL = import.meta.env.VITE_BASE_URL;
const handleAvatarSuccess = (
  res
) => {
  console.log(formItem.value.image);

  if (res.code == 200) {
    formItem.value.image = res.data;
  }
}
// 返回上一页的跳转
const onBack = () => {
  router.back()
  formItem.value = {}
}
// 点击跳转的 判断有没有id 再渲染新增或者修改
const addOrUpdate = computed(() => {
  if (route.params._id) {
    return '编辑'
  } else {
    return '新增'
  }
})
const rules = ref({
  name: [
    { required: true, message: '服务包名称不能为空', trigger: 'blur' },

  ],
  type: [
    { required: true, message: '服务包类型不能为空', trigger: 'blur' },

  ],
  price: [
    { required: true, message: '订购价格不能为空', trigger: 'blur' },

  ],
  period: [
    {
      required: true,
      message: '签约周期不能为空',
      trigger: 'blur',
    },
  ],
})
const columns = [
  {
    label: '项目编号',
    prop: '_id',
  },
  {
    label: '项目名称',
    prop: 'name',
  },
  {
    label: '次数',
    prop: 'count',
  },
  {
    label: '项目类型',
    prop: 'type'
  },
  {
    label: '项目介绍',
    prop: 'intro',
    width: '300px'
  },
  {
    label: '操作',
    prop: 'action'
  },
]
</script>

<style scoped lang="scss">
/* 修改 placeholder 颜色 */
::v-deep .el-input__inner::placeholder {
  color: #ccc;
  /* 浅灰色，可按需调整 */
}

.top-outer-layer {
  display: flex;
  height: 45px;
  margin-bottom: 10px;
  border-bottom: 1px solid #e5e5e5;
}

.border-left {
  width: 6px;
  height: 24px;
  background-color: rgba(41, 132, 248, 1);
  border-radius: 10px;
}

.add-text {
  margin-left: 10px;
  font-size: 18px;
  color: rgba(51, 51, 51, 0.898039215686275);

}

.ser-info {
  font-size: 16px;
  color: #333333;
  margin-top: 20px;
  margin-bottom: 20px;
}

.form-image {
  width: 223px;
  height: 120px;
  border: 1px solid #f2f2f2;
  background-color: #f9f9f9;
  border-radius: 10px;
  font-size: 14px;
  color: #ccc;
  text-align: center;
  line-height: 120px;
  cursor: pointer;
}

.load-image:hover {
  color: var(--el-color-primary);
}

.el-upload__tip {
  color: #ccc;
  font-size: 12px;
}

.add-button {
  display: flex;
  justify-content: space-between;
  margin-top: 20px;
  margin-bottom: 20px;
}

.write-img {
  width: 15px;
  height: 16px;
  margin: 10px 10px;
}

.add-one {
  color: var(--el-color-primary);
  cursor: pointer;
}

.add-one:hover {
  text-decoration: underline;
}
</style>

<style>
.el-textarea__inner {
  resize: none !important;
  height: 120px;
}
</style>